package com.tanhua.dubbo.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class TimeLineService {
    @Autowired
    private MongoTemplate mongoTemplate;


    public CompletableFuture<String> saveTimeLine(Long userId, ObjectId publisId) {
        try {
            //1.获取用户的好友列表
            Query query = Query.query(Criteria.where("userId").is(userId));
            List<Users> userss = mongoTemplate.find(query, Users.class);
            if (CollUtil.isEmpty(userss)) {
                return CompletableFuture.completedFuture("ok");
            }
            //将动态写入到所有好友的时间线表中
            for (Users users : userss) {
                TimeLine timeLine = new TimeLine();
                timeLine.setPublishId(publisId);
                timeLine.setId(ObjectId.get());
                timeLine.setUserId(userId);
                timeLine.setDate(System.currentTimeMillis());
                //写入好友的时间线
                mongoTemplate.save(timeLine, "quanzi_time_line_" + users.getFriendId());
            }
        } catch (Exception e) {
            //写入好友时间线失败
            log.error("写入好友时间线失败!");
            return CompletableFuture.completedFuture("error");
        }
        return CompletableFuture.completedFuture("ok");
    }
}
